/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.service.prioritySend;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.OfflineEdiOrder;
import com.topisv.tms.entity.OrderBackTask;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.mybatis.service.CommonService;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.prioritySend.OfflineEdiOrderDao;
import com.topisv.tms.repository.prioritySend.OrderBackTaskDao;
import com.topisv.tms.service.ExpressConfigureService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.task.interfacetask.SelfException;

import net.sf.json.JSONObject;

/**
 * 天天订单回传任务执行方法
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
@Component
@Transactional(readOnly = true)
public class OrderBackTaskProcessService{
	private static final Logger logger = LoggerFactory.getLogger(OrderBackTaskProcessService.class);

	private static final String wmsOrder = "系统订单";
	private static final String offlineOrder = "导入订单";
	
	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private WarehouseAddressService warehouseAddressService;
	@Autowired
	private OfflineEdiOrderDao offlineEdiOrderDao;
	@Autowired
	private OrderBackTaskDao orderBackTaskDao;
	@Autowired
	private PrioritySendService prioritySendService;
	@Autowired
	private ExpressConfigureService expressConfigureService;

	
	public void process(OrderBackTask task) throws Exception {
		String type = task.getType();

		if ("系统订单".equals(type)) {
			wmsOrderSendTTKDEX(task);
		} else if ("导入订单".equals(type)) {
			offlineOrderSendTTKDEX(task);
		} else {
			throw new SelfException("未知的接口类型!");
		}
	}

	/**
	 * 能容系统订单回传给天天
	 * 
	 *
	 * @param task
	 *            [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public void wmsOrderSendTTKDEX(OrderBackTask task) throws Exception {
		
		String status = "fail";

		//查询基础信息:订单信息，仓库地址，快递配置信息
		EdiOrder ediOrder = ediOrderDao.findByOrdeno(task.getRelatedNo());
		WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(ediOrder.getWarehouseCode());
		ExpressConfigure expressConfigure = expressConfigureService.findByWarehouseAndCompany(ediOrder.getWarehouseCode(), "TTKDEX");
		
		if(expressConfigure == null ){
			 expressConfigure = expressConfigureService.findByWarehouseAndCompany("HZTT", "TTKDEX");
		}
		
		//封装成对象
		OfflineEdiOrder oEdiOrder = new OfflineEdiOrder();
		oEdiOrder.setOrdeno(ediOrder.getOrdeno());
		oEdiOrder.setMailNo(ediOrder.getMailNo());
		oEdiOrder.setSendna(warehouseAddress.getContact());
		oEdiOrder.setSendProvna(warehouseAddress.getProvName());
		oEdiOrder.setSendCityna(warehouseAddress.getCityName());
		oEdiOrder.setSendAddres(warehouseAddress.getAddress());
		oEdiOrder.setSendMobile(warehouseAddress.getMobile());
		oEdiOrder.setSendTeleph("");
		oEdiOrder.setRecena(ediOrder.getRecena());
		oEdiOrder.setProvna(ediOrder.getProvna());
		oEdiOrder.setCityna(ediOrder.getCityna());
		oEdiOrder.setAddres(ediOrder.getAddres());
		oEdiOrder.setMobile(ediOrder.getMobile());
		oEdiOrder.setTeleph(ediOrder.getTeleph());

		// 发送天天订单回传接口
		JSONObject resultJsonObject = prioritySendService.getTTKDEXResult(oEdiOrder, expressConfigure);
		logger.info("{}==定时器系统订单回传结果=={}", ediOrder.getOrdeno(), resultJsonObject);
		
		if ("1000".equals(resultJsonObject.get("code"))) {
			status = "success";
		} else {
			status = "fail";
		}

		//更新任务状态和订单状态
		updateData(task, status);
	}
	
	
	/**
	 * 线下导入订单回传给天天
	 * 
	 *
	 * @param task
	 *            [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public void offlineOrderSendTTKDEX(OrderBackTask task) throws Exception {
		
		String status = "fail";

		//查询基础信息:订单信息，快递配置信息
		OfflineEdiOrder oEdiOrder = offlineEdiOrderDao.findByOrdeno(task.getRelatedNo());
		ExpressConfigure expressConfigure = expressConfigureService.findByWarehouseAndCompany(oEdiOrder.getWarehouseCode(), "TTKDEX");

		// 发送天天订单回传接口
		JSONObject resultJsonObject = prioritySendService.getTTKDEXResult(oEdiOrder, expressConfigure);
		logger.info("{}==定时器导入订单回传结果=={}", oEdiOrder.getOrdeno(), resultJsonObject);
		
		if ("1000".equals(resultJsonObject.get("code"))) {
			status = "success";
		} else {
			status = "fail";
		}
		
		//更新任务状态和订单状态
		updateData(task, status);
		
	}

	/**
	 * 更新任务状态和订单状态
	 * 
	 *
	 * @param task
	 * @param status [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@Transactional(readOnly =  false, rollbackFor = Exception.class)
	public void updateData(OrderBackTask task, String status) {
		
		try {
			// 更新订单回传状态
			if (wmsOrder.equals(task.getType())) {
			
				ediOrderDao.updateReturnStatus(status, task.getRelatedNo());
				
			} else if (offlineOrder.equals(task.getType())) {

				offlineEdiOrderDao.updateReturnStatus(status, task.getRelatedNo());
				
			}

			// 更新任务信息
			orderBackTaskDao.updateStatus(status, task.getId(), new Date());
			
		} catch (Exception e) {
			logger.error("{}== 更新任务状态和订单状态失败=={}", task.getId(),e);
		}
	}

}
